#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import requests

from wingman import logger
from wingman.common.error import ErrorCode
from config.rules_help import CICD_HELP
from config.system import (
    JENKINS_DEV_WEBHOOK, JENKINS_DEV_USER, JENKINS_DEV_PASSWD, 
    JENKINS_TEST_WEBHOOK, JENKINS_TEST_USER, JENKINS_TEST_PASSWD, 
    JENKINS_PRE_WEBHOOK, JENKINS_PRE_USER, JENKINS_PRE_PASSWD, 
    JENKINS_PROD_WEBHOOK, JENKINS_PROD_USER, JENKINS_PROD_PASSWD
   )


class JenkinsMap:
    """向JENKINS发送请求"""

    def getcode_jenkins(self, env_name, task):
        """
        dev环境:开发环境,外部用户无法访问,开发人员使用,版本变动大。
        test环境:测试环境,外部用户无法访问,专门给测试人员使用的,版本相对稳定。
        pre环境:验证环境,但是服务器配置相对低,其它和生产环境一样。
        pro环境:生产环境,面向外部用户的环境,连接上互联网即可访问的生产环境。
        """
        credentials = {
            "dev": (JENKINS_DEV_WEBHOOK, JENKINS_DEV_USER, JENKINS_DEV_PASSWD),
            "test": (JENKINS_TEST_WEBHOOK, JENKINS_TEST_USER, JENKINS_TEST_PASSWD),
            "pre": (JENKINS_PRE_WEBHOOK, JENKINS_PRE_USER, JENKINS_PRE_PASSWD),
            "prod": (JENKINS_PROD_WEBHOOK, JENKINS_PROD_USER, JENKINS_PROD_PASSWD)
        }

        if env_name in credentials:
            WEBHOOK, USER, PASSWD = credentials[env_name]
        else:
            WEBHOOK, USER, PASSWD = credentials["test"]

        if task in CICD_HELP:
            try:
                url = f"http://{USER}:{PASSWD}@{WEBHOOK}{CICD_HELP[task]}"
                response = requests.post(url, data={'key1': 'value1', 'key2': 'value2'})
                logger.debug(ErrorCode.DEBUG.value, response.status_code, __name__)
                logger.debug(ErrorCode.DEBUG.value, response.json(), __name__)
                result = { "title": "cicd bot", "result_msg": "已发送指令至Jenkin,请稍后......"}
            except requests.exceptions.RequestException as e:
                result = { "title": "jenkins_map", "result_msg": f"请求Jenkins时出错: {e},发送指令至Jenkin失败,状态码:{response.status_code}"}
                logger.error(ErrorCode.JEKINS_REQUESTS.value, str(e), __name__)
            except Exception as e:
                result = { "title": "jenkins_map", "result_msg": f"发生错误: {str(e)},发送指令至Jenkin失败,状态码:{response.status_code}"}
                logger.error(ErrorCode.JEKINS_REQUESTS.value, str(e), __name__)
            finally:
                # logger.info(ErrorCode.SUCCESS.value, result, __name__)
                return result
